package com.luhuiguo.cms.server.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;

import com.luhuiguo.cms.server.entity.Article;
import com.luhuiguo.cms.server.service.ArticleService;
import com.luhuiguo.cms.server.service.MapperService;
import com.luhuiguo.cms.shared.model.ArticleModel;
import com.luhuiguo.cms.shared.model.ArticleStatus;
import com.luhuiguo.cms.shared.rpc.CreateArticle;
import com.luhuiguo.cms.shared.rpc.CreateArticleResult;
import com.luhuiguo.gwt.dispatcher.server.ActionHandler;
import com.luhuiguo.gwt.dispatcher.server.ExecutionContext;
import com.luhuiguo.gwt.dispatcher.shared.exception.ActionException;
import com.luhuiguo.gwt.validation.server.ServerValidation;

@Component
public class CreateArticleHandler implements ActionHandler<CreateArticle, CreateArticleResult> {

    @Autowired
    private MapperService mapperService;

    @Autowired
    private ArticleService articleService;

    @Override
    @PreAuthorize("isAuthenticated()")
    public CreateArticleResult execute(CreateArticle action, ExecutionContext context) throws ActionException {

        Article a = mapperService.map(action.get(), Article.class);
        
        new ServerValidation(false).length(a.getTitle(), 1, 100, "title").validate();

        
        a.setStatus(ArticleStatus.STATUS_APPROVED);
        articleService.saveArticle(a);
        return new CreateArticleResult(mapperService.map(a, ArticleModel.class));

    }

    @Override
    public Class<CreateArticle> getActionType() {
        return CreateArticle.class;
    }

    @Override
    public void rollback(CreateArticle action, CreateArticleResult result, ExecutionContext context)
            throws ActionException {

    }

}
